package artist.graphic.cn.UI.Fragment;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.iflytek.cloud.speech.SpeechConstant;
import com.iflytek.cloud.speech.SpeechError;
import com.iflytek.cloud.speech.SpeechListener;
import com.iflytek.cloud.speech.SpeechSynthesizer;
import com.iflytek.cloud.speech.SpeechUser;
import com.iflytek.cloud.speech.SynthesizerListener;
import com.youth.banner.listener.OnBannerListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import artist.graphic.cn.R;
import artist.graphic.cn.UI.HTMLActivity;
import artist.graphic.cn.UI.MainActivity;
import artist.graphic.cn.UI.UnlockActivity;
import artist.graphic.cn.Utils.PicassoImageLoader;
import artist.graphic.cn.Utils.ToastShow;
import artist.graphic.cn.http.GetNetWorkState;
import artist.graphic.cn.http.baidutranslate.TransApi;

import static android.content.Context.TELEPHONY_SERVICE;

/**
 * Created by wanghuanlong on 2018/1/19.
 */

public class MainFragment extends Fragment implements View.OnClickListener,SynthesizerListener {

    //百度查询相关的所调用变量
    private static final String APP_ID = "20171228000110093";
    private static final String SECURITY_KEY = "QleSfggfc0kuxNdnpoL4";
    private TransApi api;
    private String query;
    private String result;
    private String dst;

    //语音播放相关
    private SpeechSynthesizer speechSynthesizer;

    //页面控件
    private com.youth.banner.Banner mBanner;
    private EditText editText, editText2;
    private Drawable drawable;
    private Spinner spinner, spinner2;
    private ImageView iv_google_translate,iv_sound;
    private String[] url;
    private String[] articleContent;

    private ConnectivityManager mConnectivity;
    //检查网络连接
    private NetworkInfo info;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    editText2.setText(dst);
                    break;
                default:
                    break;
            }
        }

    };


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_main, container, false);

        initBlock(view);

        SpeechUser.getUser().login(getActivity(), null, null, "appid=5a6696e1", listener);
        setParam(); //初始化语音播报
        return view;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.el_hearing_enhancement:
                Toast.makeText(getContext(), "即将实现该功能，敬请期待", Toast.LENGTH_SHORT).show();
                break;
            case R.id.el_message:
                Toast.makeText(getContext(), "该功能还未开发，敬请期待", Toast.LENGTH_SHORT).show();
                break;

            case R.id.iv_google_translate:
                Bundle bundle = new Bundle();
                String url = "https://translate.google.cn/";
                bundle.putString("html", url);
                Intent intent = new Intent(getContext(), HTMLActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
                break;

            case R.id.iv_sound:
                String text = editText2.getText().toString();    //把单词提取出来
                speechSynthesizer.startSpeaking(text,this);          //讯飞 播放声音
                break;
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initBlock(View view) {
        mBanner = (com.youth.banner.Banner) view.findViewById(R.id.top_banner);
        iv_google_translate = (ImageView) view.findViewById(R.id.iv_google_translate);
        iv_google_translate.setOnClickListener(this);
        iv_sound = (ImageView) view.findViewById(R.id.iv_sound);
        iv_sound.setOnClickListener(this);
        spinner2 = (Spinner) view.findViewById(R.id.spinner2);
        setCursListener(view);
        editText = (EditText) view.findViewById(R.id.editText);
        editText2 = (EditText) view.findViewById(R.id.editText2);
        editText.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // et.getCompoundDrawables()得到一个长度为4的数组，分别表示左右上下四张图片
                drawable = editText.getCompoundDrawables()[2];
                //如果右边没有图片，不再处理
                if (drawable == null)
                    return false;
                //如果不是按下事件，不再处理
                if (event.getAction() != MotionEvent.ACTION_UP)
                    return false;
                if (event.getX() > editText.getWidth()
                        - editText.getPaddingRight()
                        - drawable.getIntrinsicWidth()) {
                    editText.setText("");

                }
                return false;
            }
        });

        editText2.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // et.getCompoundDrawables()得到一个长度为4的数组，分别表示左右上下四张图片
                drawable = editText2.getCompoundDrawables()[2];
                //如果右边没有图片，不再处理
                if (drawable == null)
                    return false;
                //如果不是按下事件，不再处理
                if (event.getAction() != MotionEvent.ACTION_UP)
                    return false;
                if (event.getX() > editText2.getWidth()
                        - editText2.getPaddingRight()
                        - drawable.getIntrinsicWidth()) {

                    if (editText2.getText() != null)
                        copyLink(editText2.getText().toString());

                }
                return false;
            }
        });


        spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                checkBeforeTranslation();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {// Another interface callback
            }
        });

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                checkBeforeTranslation();
            }
        });

        int count = 3;
        articleContent = new String[count];
        articleContent[0] = "http://www.wendu.com/";
        articleContent[1] = "http://sku.duia.com/4";
        articleContent[2] = "https://user.qzone.qq.com/1105436599/infocenter";

        url = new String[count];
        url[0] = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1516705007633&di=f0c07b0bb0a7145a4dda37df68bcf25e&imgtype=0&src=http%3A%2F%2Fpic32.photophoto.cn%2F20140903%2F0017030217044641_b.jpg";
        url[1] = "http://tu.duia.com/contentPic/20180115/3d8cc7ed-c21b-4ac2-b9c3-a834603a6ce1.jpg";
        url[2] = "http://b149.photo.store.qq.com/psb?/V14PPab23Vr2of/BnoRwNPt2kfyFSBtgq.ek2gXGc6zAC3gDZMrU0gFkUw!/b/dEiu0ljWIAAA&bo=WAOAAgAAAAAFB*0!&rf=viewer_4";

        List<String> urls = new ArrayList<String>();
        for (int i = 0; i < count; i++) {
            urls.add(url[i]);
        }
        mBanner.setImages(urls).setImageLoader(new PicassoImageLoader(R.drawable.ic_guide1)).start();
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                try {

                    Log.i("点击", position + "show");


                    final int i = position;

                    Handler handler = new Handler();


                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Goto(i);
                        }
                    });


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });
    }

    //banner上对应的图片跳转
    public void Goto(int i) {


        Uri uri = Uri.parse(articleContent[i]);

        Bundle mainPragm = new Bundle();

        String html = articleContent[i];

        mConnectivity = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

        info = mConnectivity.getActiveNetworkInfo();

        GetNetWorkState getNetWorkState = new GetNetWorkState();
        Log.i("请检查网络", "" + getNetWorkState.isWifi(this.getActivity()) + getNetWorkState.isMobile(this.getActivity()) + getNetWorkState.isNet(info, mConnectivity));

        if (getNetWorkState.isNet(info, mConnectivity)) {
            mainPragm.putString("html", html);
            Intent it = new Intent(this.getActivity(), HTMLActivity.class);
            it.putExtras(mainPragm);
            startActivity(it);
        } else {

            new ToastShow(this.getActivity(), "请检查网络！");

        }

    }


    public void checkBeforeTranslation(){
        //如果在翻译之前的编辑框内只有一个空格的话会出异常的，所以进行了异常处理
        String str = editText.getText().toString();
        int i = str.length();

        if (i == 1 || i == 0) {
            editText.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);

            editText2.setText("");
        } else {
            editText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.button_clear, 0);
        }
        int j;
        boolean isAllSpace = false;

        for (j = 0; j < i; j++) {
            if (str.charAt(j) == ' ') {

                isAllSpace = true;
            } else {
                isAllSpace = false;
                break;
            }
        }
        mConnectivity = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        info = mConnectivity.getActiveNetworkInfo();
        GetNetWorkState getNetWorkState = new GetNetWorkState();

        if (isAllSpace == false){

            if(getNetWorkState.isNet(info, mConnectivity))
                getWhatLanguage();
            else{
                new ToastShow(getActivity().getApplication(), "请检查网络！");
            }
        }
    }



    public void getWhatLanguage() {

        if (editText.getText().toString().equals(""))   //如果在翻译的前的编辑框内没用填写什么，那么就什么也不做
        {

        } else {
            if ("英语".equals(spinner2.getSelectedItem().toString())) {

                final String want_to_get_the_language = "en";
                translation(want_to_get_the_language);
            }

            if ("简体中文".equals(spinner2.getSelectedItem().toString())) {

                final String want_to_get_the_language = "zh";
                translation(want_to_get_the_language);
            }

            if ("繁体中文".equals(spinner2.getSelectedItem().toString())) {

                final String want_to_get_the_language = "cht";
                translation(want_to_get_the_language);
            }

            if ("日语".equals(spinner2.getSelectedItem().toString())) {
                final String want_to_get_the_language = "jp";
                translation(want_to_get_the_language);

            }

            if ("韩语".equals(spinner2.getSelectedItem().toString())) {

                final String want_to_get_the_language = "kor";
                translation(want_to_get_the_language);

            }
        }

    }


    public void translation(String language) {

        final String want_to_get_the_language = language;
        new Thread(new Runnable() {
            @Override
            public void run() {
                query = editText.getText().toString();
                api = new TransApi(APP_ID, SECURITY_KEY);
                result = api.getTransResult(query, "auto", want_to_get_the_language);
                result = result.substring(result.indexOf("["), result.indexOf("]") + 1);
                try {
                    JSONArray jsonArray = new JSONArray(result);
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    dst = jsonObject.getString("dst");

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                mHandler.obtainMessage(0).sendToTarget();
            }
        }).start();

    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void setCursListener(View view) {
        Spinner spinner = (Spinner) view.findViewById(R.id.spinner2);
        String[] str = {"简体中文", "繁体中文", "英语", "日语", "韩语"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.my_spinner, str);
        spinner.setAdapter(adapter);


        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = (TextView) view;
                tv.setTextColor(getResources().getColor(R.color.white));    //设置颜色
                tv.setTextSize(12.0f);    //设置大小
                tv.setGravity(android.view.Gravity.CENTER_HORIZONTAL);   //设置居中
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

    }
    @SuppressLint("NewApi")
    private void copyLink(String text) {
        ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        if (!text.isEmpty()) {
            cm.setText(text);
            Toast.makeText(getContext(),"已经复制到剪切板",Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 初始化语音播报
     */
    public void setParam() {
        speechSynthesizer = SpeechSynthesizer.createSynthesizer(getActivity());
        speechSynthesizer.setParameter(SpeechConstant.VOICE_NAME, "xiaoyan");
        speechSynthesizer.setParameter(SpeechConstant.SPEED, "50");
        speechSynthesizer.setParameter(SpeechConstant.VOLUME, "50");
        speechSynthesizer.setParameter(SpeechConstant.PITCH, "50");
    }


    private SpeechListener listener = new SpeechListener() {

        //消息回调
        @Override
        public void onEvent(int arg0, Bundle arg1) {
            // TODO Auto-generated method stub

        }

        //数据回调
        @Override
        public void onData(byte[] arg0) {
            // TODO Auto-generated method stub

        }

        //结束回调（没有错误）
        @Override
        public void onCompleted(SpeechError arg0) {
            // TODO Auto-generated method stub

        }
    };


    @Override
    public void onSpeakBegin() {

    }

    @Override
    public void onBufferProgress(int i, int i1, int i2, String s) {

    }

    @Override
    public void onSpeakPaused() {

    }

    @Override
    public void onSpeakResumed() {

    }

    @Override
    public void onSpeakProgress(int i, int i1, int i2) {

    }

    @Override
    public void onCompleted(SpeechError speechError) {

    }
}